#include "udp_client.hpp"

static void usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n" << std::endl;
}

void *recver(void *args)
{
    int sock = *(static_cast<int *>(args));

    while (true)
    {
        //接收
        char buffer[2048];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int n = recvfrom(sock, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &len);
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << buffer << std::endl;//1
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    // 创建socket接口，打开网络文件
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(SOCKET_ERR);
    }

    // 明确server是谁
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);

    pthread_t tid;
    pthread_create(&tid, nullptr, recver, &sock);

    while (true)
    {
        // 用户输入
        std::string message;
        std::cerr << "Please Enter Your Message# ";//2
        // std::cin >> message;
        std::getline(std::cin, message);

        // 发送
        // 在我们首次系统调用发送数据时，OS会在底层随机选择cilentport+自己的IP进行bind，并构建发送的数据报文
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
    }

    return 0;
}